<?php
/**
 * tmaic.com 
 * ============================================================================
 * * 版权所有 2020-2030 tmaic，并保留所有权利。
 * 网站地址: http://www.tmaic.com；
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和
 * 使用；不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * $Author: pangxianfei
 * $email:421339244@qq.com
 * $phone:18929142226
 * $date 2020-11-13
*/
namespace App\Http\Controllers\Admin;

use App\Http\Controllers\AdminController;
use Illuminate\Http\Request;
use App\Http\Requests\ArticleRequest;
use App\Models\Article\MainArticle;
use App\Models\Article\ArticleTranslation;
use Illuminate\Support\Facades\Response;
use Illuminate\Support\Facades\View;
use Illuminate\Support\Facades\DB;
use App\Services\QiniuServices;

class ArticleController extends AdminController
{
    /**
     * 文章列表
     * @return \Illuminate\Contracts\View\View
     */
    public function index()
    {
        $categories = $this->getColumnClass();
        return View::make('admin.article.index', compact('categories'));
    }

    /**
     * 数据接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function data(Request $request)
    {

        $created_at = $request->get('created_at') ?? null;
        $lang = $request->get('lang', 'zh');
        $model = ArticleTranslation::query();
        if ($lang) {
            $model = $model->where('locale', $lang);
        }
        if ($request->get('title')) {
            $model = $model->where('title', 'like', '%' . $request->get('title') . '%');
        }
        if (!empty($created_at)) {
            $startime = substr($created_at, 0, 20);
            $endtime = substr($created_at, -20, 20);
            $model = $model->whereBetween('created_at', [$startime, $endtime]);
        }
        $res = $model->with('column')->by()->paginate($request->get('limit', 10));
        $data = [
            'code' => 0,
            'msg' => '正在请求中...',
            'count' => $res->total(),
            'data' => $res->items(),
        ];
        return Response::json($data);
    }

    public function create()
    {
        //分类
        $categories = $this->getColumnClass('Article');
        return View::make('admin.article.create', compact('categories'));
    }

    /**
     * 添加
     * @param ArticleRequest $request
     * @return \Illuminate\Http\RedirectResponse
     */
    public function store(ArticleRequest $request)
    {
        $data = $request->except(['_token', 'file']);
		$request = (object)$data;
        DB::beginTransaction();
        try {
            $article = new MainArticle();
            $article->name = (string)$request->title;
            $article->online = 1;
            foreach (config('translatable.locales') as $locale => $item) {
				$article = $this->createItem($article,$request,$locale);
            }
            $article->save();
            DB::commit();
            return Response::json(['code' => 0, 'msg' => '添加成功', 'data' => '添加成功', 'url' => route('admin.article')]);
        } catch (\Exception $exception) {
            DB::rollback();

        }
        return Response::json(['code' => 0, 'msg' => '添加失败', 'data' => '添加失败']);
    }


    /**
     * 更新
     * @param $id
     * @return \Illuminate\Contracts\View\View
     */
    public function edit(Request $request)
    {
        $id = (int)$request->get('id');
        $locale = $request->get('lang');
        $article = MainArticle::whereTranslation('id', $id)->firstOrFail();
        $article = $article->translate($locale);
        //文章栏目列表
        $categories = $this->getColumnClass('Article');

        return View::make('admin.article.edit', compact('article', 'categories', 'locale'));
    }

    /**
     * 更新
     * @param ArticleRequest $request
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update(ArticleRequest $request)
    {
        $id = (int)$request->get('id');
        if(empty($id))  return Response::json(['code' => 1, 'msg' => '非法操作']);
        $data = $request->except(['_token', 'file']);
		$request = (object)$data;
		//明细表记录
        $ArticleTranslation = ArticleTranslation::where('id', $id)->firstOrFail();
		//主表记录
        $MainArticle = MainArticle::whereTranslation('id', $id)->firstOrFail();
		$MainArticle->name = $request->title;
		$MainArticle->column_id = $request->column_id;
        DB::beginTransaction();
        try {
            foreach (config('translatable.locales') as $locale => $item) {
				//栏目ID更新
                $MainArticle->translateOrNew($locale)->column_id = (int)$request->column_id;
				//判断是否有翻译 则更新
				if($MainArticle->hasTranslation($locale)){
					$MainArticle->translateOrNew($locale)->title = (string)$request->title;
					$MainArticle->translateOrNew($locale)->seo_title = (string)$request->seo_title;
					$MainArticle->translateOrNew($locale)->flag = $request->flag;
					$MainArticle->translateOrNew($locale)->seo_title = (string)$request->seo_title;
					$MainArticle->translateOrNew($locale)->keywords = (string)$request->keywords;
					$MainArticle->translateOrNew($locale)->description = (string)$request->description ;
					$MainArticle->translateOrNew($locale)->thumb = (string)$request->thumb;
					$MainArticle->translateOrNew($locale)->body = $request->body;
				}
				//没有国家的语言就添加
				else{
					$MainArticle = $this->createItem($MainArticle,$request,$locale);
				}
				
            }
			//end foreach

            $MainArticle->save();
			$ArticleTranslation->update($data);
            DB::commit();
            return Response::json(['code' => 0, 'msg' => '更新成功', 'data' => '更新成功']);
        } catch (\Exception $exception) {
            DB::rollback();
        }
        return Response::json(['code' => 0, 'msg' => '更新失败', 'data' => '更新失败']);
    }
    /**
	* 更新状态
    * @param $id int
	**/
    public function updateAjax(Request $request)
    {
        $id = (int)$request->get('id');
        $ArticleTranslation = ArticleTranslation::where('id', $id)->first();
        $data = $request->all();
        DB::beginTransaction();
        try {
            $ArticleTranslation->update($data);
            DB::commit();
            return Response::json(['code' => 0, 'msg' => '更新成功', 'data' => '更新成功']);
        } catch (\Exception $exception) {
            DB::rollback();

        }
        return Response::json(['code' => 1, 'msg' => '更新失败', 'data' => $exception->getMessage()]);
    }

    /**
	* 删除文章
    * @param $ids array
	**/
    public function destroy(Request $request,QiniuServices $qiniu)
    {
        $mids = (array)$request->get('mid');
        if (!is_array($mids)) {
            return Response::json(['code' => 1, 'msg' => '请选择删除项']);
        }
        DB::beginTransaction();
        try {
            foreach ($mids as $id){
			    $mainArticle = MainArticle::where('mid', $id)->firstOrFail();
				foreach($mainArticle->translations	 as $item){
				//删除产品资源
				 $qiniu->objFromDelete($item);
				 //记录文章记录
				}
				$mainArticle->deleteTranslations();
            }
            DB::commit();
            return Response::json(['code' => 0, 'msg' => '删除成功']);
        } catch (\Exception $exception) {
            DB::rollback();
            return Response::json(['code' => 1, 'msg' => '删除失败', 'data' => $exception->getMessage()]);
        }
    }
	
	

	private function createItem($article,$request,$locale){
		
				$article->translateOrNew($locale)->column_id = (int)$request->column_id;
				$article->translateOrNew($locale)->title = (string)$request->title;
				$article->translateOrNew($locale)->seo_title = (string)$request->seo_title;
				$article->translateOrNew($locale)->flag = $request->flag;
				$article->translateOrNew($locale)->seo_title = (string)$request->seo_title;
				$article->translateOrNew($locale)->keywords = (string)$request->keywords ?? '';
				$article->translateOrNew($locale)->description = (string)$request->description ?? '';
				$article->translateOrNew($locale)->thumb = (string)$request->thumb ?? '';
				$article->translateOrNew($locale)->body = $request->body ?? '';
				$article->translateOrNew($locale)->updated_at = now();
				$article->translateOrNew($locale)->created_at = now();
			return $article;
	}
	
	
	
	
	
}
